package com.csnf.servlet;

import com.csnf.entity.User;
import com.csnf.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet({"/getUser","/editUser","/updateUser"})
public class UserServlet extends HttpServlet {
    UserService userService = new UserService();  //实例化业务层

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        Integer user_id = Integer.valueOf(req.getParameter("user_id"));
        String user_name = req.getParameter("user_name");
        String user_nickname = req.getParameter("user_nickname");
        Boolean flag = false;
        try {
            flag = userService.updateUser(new User(user_id,user_name,user_nickname));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (flag) {
            getUserByNickName(req, resp);
        }else {
            req.setAttribute("msg","修改未成功!");
            req.getRequestDispatcher("editUser.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        switch (path){
            case "/getUser":   //通过昵称找用户列表
                getUserByNickName(req, resp);
                break;
            case "/editUser":  //通过id查找用户信息
                getUserById(req, resp);
                break;
        }
    }

    /**
     * 通过id查找用户信息
     * @param req
     * @param resp
     */
    private void getUserById(HttpServletRequest req, HttpServletResponse resp) {
        String user_id = req.getParameter("user_id");
        try {
            User user = userService.getUserById(Integer.valueOf(user_id));
            req.setAttribute("user",user);
            req.getRequestDispatcher("editUser.jsp").forward(req, resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 通过昵称查用户列表
     * @param req
     * @param resp
     */
    private void getUserByNickName(HttpServletRequest req, HttpServletResponse resp) {
        String queryName = req.getParameter("queryName"); //从请求获取查询条件
        queryName = queryName==null?"":queryName;
        try {
            List<User> userList =  userService.getUserByNickName(queryName); //通过昵称，查询得到用户集合
            req.setAttribute("userList",userList); //将用户信息存放到请求对象
            req.getRequestDispatcher("success.jsp").forward(req, resp);  //转发到主页显示
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
